package com.tplhk.valid.validator;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @ClassName : StrLengthValidator
 * @Description : TODO
 * @Author : taiping
 * @Date: 2020/11/9 10:19
 **/
@Data
public class StrLengthValidator implements ConstraintValidator<StrLength, String> {
    private int min;

    private int max;

    @Override
    public void initialize(StrLength strLength) {
        this.min = strLength.min();
        this.max = strLength.max();
    }

    @Override
    public boolean isValid(String str, ConstraintValidatorContext constraintValidatorContext) {
        //为空不做校验
        if (StringUtils.isEmpty(str)) {
            return true;
        }

        if (str.length() < min) {
            return false;
        }

        if (str.length() > max) {
            return false;
        }

        return true;
    }
}
